// index.ts
// 获取应用实例
import msg from "../../utils/msg";
import User from "../../utils/user";
import { GetJoinActivity, GetCourse } from "../../utils/request/api";
import { Course } from "../curriculum/interface";
import { SignParamActivity,SignParamCourse, goToSignInActivity,goToSignInCourse } from "../signIn/util";
const app = getApp<IAppOption>();
var user = new User;
interface card{
  id:number | string,
  title:string,
  content:string,
  date:string,
  sort:string,//第几节上课，用于排序
}
interface Acticity{
  id:number | string,
	title:string,
	place:string,
	start_time:string,
	end_time:string,
}
Page({
  data: {
    courseData: [
    ] as Array<card>,
    activityData: [
    ] as Array<card>,
    //课程信息
    curriculum_msg: [] as Array<Course>,
    //活动信息
    activity_msg:[] as Array<Acticity>,
    //学期开始日期
    startDate: "",
    //今天是学期的第几周
    nowWeeks:0 as number,
    //今天是周几
    day:'' as string,
    //学生学号
    s_code:user.getInfo().code
  },
  // 事件处理函数
  goToSignIn(e: any) {
    let dataset = e.currentTarget.dataset;
    if(dataset.sign_type=='活动'){
      let data: SignParamActivity = { 
        sign_type: dataset.sign_type, 
        activity_id: dataset.activity_id,
      };
      goToSignInActivity(data);
    }
    else if(dataset.sign_type=='课程'){
      let data: SignParamCourse= { 
        sign_type: dataset.sign_type, 
        course_id:dataset.course_id,
        course_msg:this._getOneCourseMsg(dataset.course_id),
      };
      goToSignInCourse(data);
    }
  },
  onLoad:async function() {
    let self = this;
    let user = new User;
    msg.Loading('获取个人信息中...')
    if(!user.cheakLogin()){
      wx.switchTab({
        url:"/pages/user/user",
      });
      msg.hideLoading();
      msg.show('请先绑定个人信息','');
      return;
    }
    //课程
    msg.Loading('获取课程中...');
    await GetCourse({ userId: user.userId })
      .then((res: any) => {
        res.data.data.course.forEach((element:Course) => {
          element.day=this._convertToChinese(element.day);
        });
        self.setData({
          curriculum_msg: res.data.data.course,
          startDate: res.data.data.startDate,
          nowWeeks: self._getWeekNumber(res.data.data.startDate),
          day:self._convertToChinese(self._getDay().toString()),
        });
        //设置全局变量
        app.globalData.nowWeeks=self._getWeekNumber(res.data.data.startDate);
        app.globalData.startDate=res.data.data.startDate;
      })
      .catch((res:any)=>{
        console.log(res);
        msg.hideLoading();
        msg.show('加载失败','可能是网络连接差或者服务器崩溃了，请稍后重试');
      });
      //
      console.log('nowWeeks=',app.globalData.nowWeeks);
    msg.hideLoading();
    this.getTodayCourse();
    //活动
    msg.Loading('获取活动中...');
    await GetJoinActivity({s_code:this.data.s_code})
    .then((res:any)=>{
      let data = res.data.data;
      this.setData({
        activity_msg:data,
      });
    });
    msg.hideLoading();
    this.getTodayActivity();
  },
  onShow(){
    msg.Loading('正在获取今日课程与活动');
    this.getTodayCourse();
    this.getTodayActivity();
    msg.hideLoading();
  },
  //跳转到课程表
  goToCurriculum() {
    //课程表只显示1-18周的课程，如果不在这个范围也要显示最近数据
    let nowWeeks=this.data.nowWeeks;
    if(nowWeeks<1) nowWeeks=1;
    if(nowWeeks>18) nowWeeks=18;
    let data ={
      curriculum_msg:this.data.curriculum_msg,
      startDate:this.data.startDate,
      nowWeeks:nowWeeks,
      day:this.data.day,
    };
    wx.navigateTo({
      url: "/pages/curriculum/curriculum"+"?data="+JSON.stringify(data),
      fail(res: any) {
        console.log(res)
      }
    })
  },
  goToActivityList(){
    wx.navigateTo({
      url:"/pages/activity/activity",
      fail(res:any){
        console.log(res)
      }
    })
  },
  /**
* @function 根据学期开始日期判断今天属于哪一周
* @param {*startDate} 学期开始日期
*/
  _getWeekNumber(startDate: string): number {
    const today = new Date(); // 获取当前日期
    const inputDate = new Date(startDate);
    if (today > inputDate) {
      const timeDiff = Math.abs(today.getTime() - inputDate.getTime());
      const daysDiff = Math.ceil(timeDiff / (1000 * 3600 * 24)); // 计算日期差
      if (daysDiff >= 18) {
        return 19;
      } else {
        const groupNumber = Math.ceil(daysDiff / 7);
        return groupNumber;
      }
    } else {

      return 0;
    }
  },
  /**
  * @function 获取今天是周几
  */
  _getDay(): number {
    const today = new Date().getDay();
    // 因为返回值范围是 0-6，需要将星期天（0）转换为 7
    return today !== 0 ? today : 7;
  },
  /**
  * @function 将阿拉伯数字转换为简体中文数字
  */
 _convertToChinese(number:string) {
  var chineseNumber = '';
  switch (number) {
    case '1':
      chineseNumber = '一';
      break;
    case '2':
      chineseNumber = '二';
      break;
    case '3':
      chineseNumber = '三';
      break;
    case '4':
      chineseNumber = '四';
      break;
    case '5':
      chineseNumber = '五';
      break;
    case '6':
      chineseNumber = '六';
      break;
    case '7':
      chineseNumber = '七';
      break;
  }
  return chineseNumber;
},
  /**
  * @function 获取今日课程
  */
  getTodayCourse(){
    //已经知道今天是学期的第几周的周几，根据课程信息判断哪些课程要上
    let nowWeeks = this.data.nowWeeks;
    if(nowWeeks<1||nowWeeks>18) return;
    let curriculum_msg=this.data.curriculum_msg;
    let day=this.data.day;
    let cardData=[] as Array<card>;
    curriculum_msg.forEach((item,index) => {
      //同一星期上课
        if(item.day==day){
          //检查这一周这门课上不上
          if(this._checkRange(item.weeks,nowWeeks)){
            let time = item.time.split('-');
            let temp:card={
              id:item.id,
              title:item.name,
              content:item.location+'-'+item.teacher,
              date:this._getCourseStartTime(time[0])+'-'+this._getCourseEndTime(time[1]),
              sort:time[0],//用于排序
            };
            cardData.push(temp);
          }
        }
    }); 
    //根据上课时间排序
    this.setData({
      courseData:this._sortArray(cardData),
    })
  },
  /**
  * @function 获取今日活动
  */
 getTodayActivity(){
   let activity_msg = this.data.activity_msg;
  let activityData=[] as Array<card>;
  for (let index = 0; index < activity_msg.length; index++) {
    let element = activity_msg[index];
    if(this._isSameDay(element.start_time)){
      let data:card={
        id:element.id,
        title:element.title,
        content:element.place,
        date:this._combineDates(element.start_time,element.end_time),
        sort:element.start_time,
      };
      activityData.push(data);
    }
  }
  //根据开始时间排序
  this.setData({
    activityData:this._sortArrayByDate(activityData),
  });
  
},
  //更改日期格式
  _combineDates(date1: string, date2: string): string {
    const [date1Part, time1Part] = date1.split(" ");
    const [date2Part, time2Part] = date2.split(" ");
  
    const [year, month, day] = date1Part.split("-");
    const [hour, minute] = time1Part.split(":");
    const [hour2, minute2] = time2Part.split(":");
  
    return `${year}-${month}-${day} ${hour}:${minute}-${hour2}:${minute2}`;
  },
  
  //检查活动日期是否是今天
  _isSameDay(dateString: string): boolean {
    const inputDate = new Date(dateString);
    
    // 获取当前日期
    const today = new Date();
    const currentYear = today.getFullYear();
    const currentMonth = today.getMonth();
    const currentDay = today.getDate();
  
    // 获取输入日期的年、月、日
    const year = inputDate.getFullYear();
    const month = inputDate.getMonth();
    const day = inputDate.getDate();
  
    return (currentYear === year && currentMonth === month && currentDay === day);
  },
  _cheakTimeValid(startDate: string, endDate: string): boolean {
    const currentTime = new Date();
    const startDateTime = new Date(startDate);
    const endDateTime = new Date(endDate);
    return currentTime >= startDateTime && currentTime <= endDateTime;
  },
  _sortArrayByDate(arr: card[]): card[] {
  return arr.sort((a, b) => {
    const dateA = new Date(a.sort);
    const dateB = new Date(b.sort);
    return dateA.getTime() - dateB.getTime();
  });
  },
  /**
  * @function 检查这一周这门课上不上
  */
  _checkRange(range: string, number: number): boolean {
    const [start, end] = range.split("-").map(Number);
    const num = number;
  
    if (Number.isNaN(start) || Number.isNaN(end) || Number.isNaN(num)) {
      throw new Error("Invalid input");
    }
  
    return num >= start && num <= end;
  },
  /**
  * @function 获取上课时间
  */
 _getCourseStartTime(index:string){
  let time = '';
  switch(index){
    case '1':
      time = '8:30';
      break;
    case '2':
      time = '9:20';
      break;
    case '3':
      time = '10:20';
      break;
    case '4':
      time = '11:10';
      break;
    case '5':
      time = '14:30';
      break;
    case '6':
      time = '15:20';
      break;
    case '7':
      time = '16:10';
      break;
      case '8':
        time = '16:50';
      break;
      case '9':
        time = '19:00';
      break;
      case '10':
        time = '19:50';
      break;
      case '11':
        time = '20:40';
      break;
  };
  return time;
 },
 /**
  * @function 获取下课时间
  */
 _getCourseEndTime(index:string){
  let time = '';
  switch(index){
    case '2':
      time = '10:00';
      break;
    case '3':
      time = '11:00';
      break;
    case '4':
      time = '11:50';
      break;
    case '5':
      time = '15:10';
      break;
    case '6':
      time = '16:00';
      break;
    case '7':
      time = '16:50';
      break;
      case '8':
        time = '17:40';
      break;
      case '9':
        time = '19:40';
      break;
      case '10':
        time = '20:30';
      break;
      case '11':
        time = '21:20';
      break;
  };
  return time;
 },
 /**
  * @function 课程列表按照sort属性排序
  */
 _sortArray(arr: card[]): card[] {
   return arr.sort((a, b) => a.sort.localeCompare(b.sort));
 },
  _getOneCourseMsg(id:number):Course{
    for(let i =0;i<this.data.curriculum_msg.length;i++){
      if(id==this.data.curriculum_msg[i].id) return this.data.curriculum_msg[i];
    }
    return {} as Course;
  },
  //休息一下吧~
  have_a_rest(){
    msg.show('今天没有课程哦~','休息一下吧');
  },
  //休息一下吧2~
  have_a_rest2(){
    msg.show('今天没有活动哦~','可以出去玩喽~');
  },
  
})
